﻿using System.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;

namespace BaseRepository.Db.UnitOfWork;

public class UnitOfWork<TDbContext> : IUnitOfWork where TDbContext : DbContext
{
    private readonly DbContext _dbContext;


    public UnitOfWork(TDbContext dbContext)
    {
        _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
    }
    public DbContext GetDbClient()
    {
        return _dbContext;
    }
    /// <summary>
    /// 获取sql连接  （由efcore管理  不需要手动的释放）
    /// </summary>
    /// <returns></returns>
    public IDbConnection GetDbConnection()
    {
        return _dbContext.Database.GetDbConnection();
    }

    /// <summary>
    /// 保存
    /// </summary>
    /// <returns></returns>
    public Task<int> SaveDbContextAsync()
    {
        return _dbContext.SaveChangesAsync();
    }
    /// <summary>
    /// 开启事务
    /// </summary>
    /// <returns></returns>
    public Task<IDbContextTransaction> BeginTranAsync()
    {
        return _dbContext.Database.BeginTransactionAsync();
    }
    /// <summary>
    /// 事务回滚
    /// </summary>
    /// <returns></returns>
    public Task CommitTranAsync()
    {
        return _dbContext.Database.CommitTransactionAsync();
    }

    public Task RollbackTranAsync()
    {
        return _dbContext.Database.RollbackTransactionAsync();
    }
}